//
//  DFBarChartView.swift
//  MYModule
//
//  Created by 李然 on 2022/9/14.
//

import UIKit
import Charts
import SwiftDate
import RxSwift
import RxRelay

public struct DFBarChartViewConfig {
    
    /// x轴文字字体
    public var xAxisLabelFont: UIFont
    
    /// x轴文字颜色
    public var xAxisLabelTextColor: UIColor
    
    /// x轴颜色
    public var xAxisLineColor: UIColor
    
    /// X轴厚度
    public var xAxisLineHeight: CGFloat
    
    /// y轴动画
    public var yAxisDuration: TimeInterval
    
    /// 点击高亮
    public var highlightPerTapEnabled: Bool
    
    
    public init(xAxisLabelFont: UIFont = .systemFont(ofSize: 10), xAxisLabelTextColor: UIColor = .black, xAxisLineColor: UIColor = .gray, xAxisLineHeight: CGFloat = 1, yAxisDuration: TimeInterval = 0, highlightPerTapEnabled: Bool = true) {
        self.xAxisLabelFont = xAxisLabelFont
        self.xAxisLabelTextColor = xAxisLabelTextColor
        self.xAxisLineColor = xAxisLineColor
        self.xAxisLineHeight = xAxisLineHeight
        self.yAxisDuration = yAxisDuration
        self.highlightPerTapEnabled = highlightPerTapEnabled
        
        
    }
}

open class DFBarChartView: BarChartView {
    
    public private(set) var selectIndex = PublishSubject<Int>()
    
    private var _animator = Animator()
    
    /// 自定义的圆柱渲染器
   public var roundRenderer: RoundBarchartRenderer? {
        
        guard let roundRenderer = renderer as? RoundBarchartRenderer else {
            return nil
        }
        
        return roundRenderer
        
    }
    
    public override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        renderer = RoundBarchartRenderer(dataProvider: self, animator: _animator, viewPortHandler: viewPortHandler)
        self.highlightFullBarEnabled = true
        
        setDefaultChart()
    }
    
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    private func setDefaultChart() {
        
    
        self.minOffset = 20
        self.noDataText = "page_no_data".language
        self.drawBarShadowEnabled = false
        self.drawValueAboveBarEnabled = false
        self.pinchZoomEnabled = false
        self.setScaleEnabled(false)
        self.drawGridBackgroundEnabled = false
        self.legend.enabled = false
        self.highlightPerTapEnabled = false
        self.highlightPerDragEnabled = false
        self.leftAxis.enabled = false
        self.rightAxis.enabled = false
        
        self.setYMin(value: 0)
        
        
        configDefauldXAxis()
    }
    
    
    
    private func configDefauldXAxis(){
        
        self.xAxis.drawGridLinesEnabled = false
        self.xAxis.labelPosition = .bottom
        self.xAxis.granularity = 1
    }
    
    
    /// 设置触摸位置，目前只用x轴位置
    public func setTouchLocation(_ location:CGPoint) {
        let higtlight = self.getHighlightByTouchPoint(CGPoint(x: location.x, y: 1))
        if let higtlight = higtlight,self.highlighted.contains(higtlight) {
            return
        }
        
        self.highlightValue(higtlight)
        if let x = higtlight?.x {
            self.selectIndex.onNext(Int(x))
        }
        
    }
    
    /// 设置markerView，柱状图上面的气泡
    public func setMarkerView(_ view:MarkerView){
        view.chartView = self
        self.marker = view
    }
    
    /// 在固定Bar 上显示marker
    public func showMarkerViewOfBar(index:Int) {
        
        setHighLightValue(x: index)
    }
    
    /// 设置barChart bar 高亮
    public func setHighLightValue(x:Int) {
        
        //        let highlight = Highlight(x: Double(x), dataSetIndex: 0, stackIndex: x)
        //        self.highlightValue(highlight, callDelegate: true)
        
        self.highlightValue(x: Double(x), dataSetIndex: 0)
    }
    
    /// 设置Y轴最大值，应是数据的最大值，数组其他数据设置一个默认最小值，为最大值的10%
    public func setYMax(value:Double){
        self.leftAxis.axisMaximum = value
        self.rightAxis.axisMaximum = value
    }
    
    /// 设置Y轴最小值
    public func setYMin(value:Double){
        self.leftAxis.axisMinimum = value
        self.rightAxis.axisMinimum = value
    }
    
    /// 设置UI配置
    public func setConfig(_ config:DFBarChartViewConfig){
        
        self.animate(yAxisDuration: config.yAxisDuration)
        self.highlightPerTapEnabled = config.highlightPerTapEnabled
        
        self.xAxis.axisLineWidth = config.xAxisLineHeight
        self.xAxis.labelFont = config.xAxisLabelFont
        self.xAxis.labelTextColor = config.xAxisLabelTextColor
        self.xAxis.axisLineColor = config.xAxisLineColor
        
        
    }
    
    /// x轴标签格式化器
    public func setXAxis(valueFormatter:IAxisValueFormatter){
        self.xAxis.valueFormatter = valueFormatter
    }
    
    /// 柱子数量
    public func setBarCount(_ count:Int){
        self.xAxis.labelCount = count
    }
    
    
    /// 设置正负柱状图
    /// - Parameters:
    ///   - barDataList: 数据源
    ///   - drawValue: 是否显示数字
    ///   - barWidth: 状图和空白条比例
    ///   - barColor: 默认颜色
    ///   - barHighLichtColor: 高亮颜色值
    public func setPositiveAndnegativeData(_ barDataList: [Double],
                        barColor:UIColor,
                        barHighLichtColor:UIColor? = nil,
                        barWidth:Double = 0.2,
                                           drawValue:Bool = false,
                                           showEmpty: Bool = false) {
        
        
        var barDataList = barDataList
        var barColor = barColor
        if showEmpty == true {
            
            if barDataList.isEmpty || barDataList.filter({ $0 != 0 }).isEmpty {
                
                barDataList = (0 ..< xAxis.labelCount).map({ _ in 0 })
                barColor = barColor.withAlphaComponent(0.1)
            }
        }
        
        print("体温")
        let entrys = barDataList.enumerated().map {(index,element) ->BarChartDataEntry in
            
            

            let entry = BarChartDataEntry(x: Double(index), y: element)
            return entry
            
        }
        print("体温")
        let dataSet = BarChartDataSet(entries: entrys, label: "")
        dataSet.colors = [barColor]
        dataSet.highlightEnabled = false
        dataSet.highlightAlpha = 1.0
        
        data = BarChartData(dataSets: [dataSet])
       

    }
    
    
    /// 设置柱状图数据
    /// - Parameters:
    ///   - barDataList: 数据源
    ///   - drawValue: 是否显示数字
    ///   - barWidth: 状图和空白条比例
    ///   - barColor: 默认颜色
    ///   - barHighLichtColor: 高亮颜色值
    public func setData(_ barDataList:[Double],
                        barColor:UIColor,
                        barHighLichtColor:UIColor? = nil,
                        barWidth:Double = 0.2,
                        drawValue:Bool = false, showEmpty: Bool = false) {
        
        
        
        
        var barDataList = barDataList
        var barColor = barColor
        if showEmpty == true {
            
            if barDataList.isEmpty || barDataList.filter({ $0 != 0 }).isEmpty {
                
                barDataList = (0 ..< xAxis.labelCount).map({ _ in 0 })
                barColor = barColor.withAlphaComponent(0.1)
            }
        }
        
        
        var highlightEnabled = false
        let barModels = barDataList.map { d ->DFBarDataModel in
            var model = DFBarDataModel(colors: [barColor], datas: [d])
            if let barHighLichtColor = barHighLichtColor {
                model.hightColor = barHighLichtColor
                highlightEnabled = true
            }
            
            return model
        }
        
        return setBarDataModels(barModels, highlightEnabled: highlightEnabled, barWidth: barWidth, drawValue: drawValue)
        
    }
    
    /// 双柱状图
    /// - Parameters:
    ///   - barDataList: 数据元，元组
    ///   - lowBarColor: 低柱颜色
    ///   - highBarColor: 高柱颜色
    ///   - barWidth: 状图和空白条比例
    ///   - drawValue: 是否显示数字
    public func setDoubleLineData(_ barDataList:[(low:Double,high:Double)] ,
                                  lowBarColor:UIColor,
                                  highBarColor:UIColor,
                                  lowBarHighLichtColor:UIColor,
                                  highBarHighLichtColor:UIColor,
                                  highlightEnabled: Bool = true,
                                  barWidth:Double = 0.2,
                                  drawValue:Bool = false){
        
        let dataLists = barDataList.map { [$0.0, $0.1] }
        let barModels = dataLists.map {record ->DFBarDataModel in
            var model = DFBarDataModel(colors: [lowBarColor, highBarColor], datas: record)
            model.hightColor = highBarHighLichtColor == .clear ? lowBarHighLichtColor : highBarHighLichtColor
            return model
        }
        return setBarDataModels(barModels, highlightEnabled: highlightEnabled, barWidth: barWidth, drawValue: drawValue)
        
    }
    
    
    /// 多颜色柱状图
    /// - Parameters:
    ///   - lineDatas: 数据源model数组
    ///   - lowBarHighLichtColor: color
    ///   - highBarHighLichtColor: color
    ///   - barWidth: width
    ///   - drawValue: boo
    public func setBarDataModels(_ barDataModels: [DFBarDataModel],
                                 highlightEnabled: Bool = true,
                                 barWidth:Double = 0.2,
                                 drawValue:Bool = false) {
        
        
        guard !barDataModels.isEmpty else {
            self.clear()
            return
        }
        
        let isSingle = barDataModels.filter { $0.colors.count > 1 }.isEmpty
        
        var data: BarChartData
        
        if isSingle {
            
            let yVals = barDataModels.enumerated().map {(index,element) ->BarChartDataEntry in
                
                let entry = BarChartDataEntry(x: Double(index), yValues: element.datas)
                return entry
                
            }
            
            let dataSet = BarChartDataSet(entries: yVals, label: "")
            if let first = barDataModels.first {
                dataSet.colors = first.colors
                if let hightColor = first.hightColor {
                    dataSet.highlightColor = hightColor
                }
                
            }
            dataSet.highlightEnabled = highlightEnabled
            dataSet.highlightAlpha = 1
            
            data = BarChartData(dataSet: dataSet)
            
        } else {
            
            let dataSets = barDataModels.enumerated().map {(index,element) ->BarChartDataSet in
                
                let entry = BarChartDataEntry(x: Double(index), yValues: element.datas)
                let dataSet = BarChartDataSet(entries: [entry], label: "")
                
                dataSet.colors = element.colors
                dataSet.highlightEnabled = highlightEnabled
                dataSet.highlightAlpha = 1
                
                if let highlightColor = element.hightColor {
                    
                    dataSet.highlightColor = highlightColor
                }
                
                return dataSet
                
            }
            
            data = BarChartData(dataSets: dataSets)
           
        }
        
        data.barWidth = barWidth
        data.setDrawValues(drawValue)
        self.data = data
        
        
    }
    
}



public struct DFBarDataModel {
    
    public var colors: [UIColor]
    public var datas: [Double]
    public var hightColor: UIColor?
    
    public init(colors: [UIColor], datas: [Double]) {
        self.colors = colors
        self.datas = datas
    }
    
}










